package com.huan;

import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class DistributeClient {
    public static void main(String[] args) throws Exception {

        DistributeClient client = new DistributeClient();

        //TODO 1 获取集群连接
        client.getConnect();
        //TODO 2 注册监听
        client.getChildren();
        //TODO 3 业务处理逻辑
        client.business();

    }
    //TODO 3 业务处理逻辑
    private void business() throws InterruptedException {
        Thread.sleep( Long.MAX_VALUE );
    }
    //TODO 2 注册监听
    private void getChildren() throws KeeperException, InterruptedException {
        List<String> children = zkClient.getChildren( "/servers", true );

        //TODO 存储服务器节点名称
        ArrayList<String> hosts = new ArrayList<String>();

        for (String child : children) {
            byte[] data = zkClient.getData( "/servers/" + child, false, null );

            hosts.add( new String(data) );
        }

        //TODO 将所有在线主机名称打印到控制台
        System.out.println(hosts);
    }


    //TODO 1 获取集群连接
    private String connectString = "huan01:2181,huan02:2181,huan03:2181";
    private int sessionTimeout = 2000;
    private ZooKeeper zkClient;
    private void getConnect() throws IOException {
        zkClient  = new ZooKeeper( connectString, sessionTimeout, new Watcher() {

            @Override
            public void process(WatchedEvent event) {
                try {
                    getChildren();
                } catch (KeeperException e) {
                    e.printStackTrace();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        } );
    }
}
